#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#include <dirent.h>
#include "cJSON.h"

#define N 3072
pthread_t tid;
char *filename = "";
int isFileInDirectory(const char *directoryPath, const char *fileName)
{
    DIR *dir;
    struct dirent *entry;
    int found = 0;

    dir = opendir(directoryPath);
    if (dir == NULL)
    {
        perror("无法打开目录");
        return 0;
    }

    while ((entry = readdir(dir)) != NULL)
    {
        if (strcmp(entry->d_name, fileName) == 0)
        {
            found = 1;
            break;
        }
    }

    closedir(dir);
    return found;
}
void *handler(void *arg)
{
    char buf[N] = {0};
    char buff[N] = {0};
    printf("will recv new connect\n");
    int sockfd, fd, ret;
    int acceptfd;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("sock  tcp NO.2 err");
        return NULL;
    }
    struct sockaddr_in dev_addr, soft_addr;
    dev_addr.sin_family = AF_INET;
    dev_addr.sin_port = htons(8001); // 传输文件端口号
    dev_addr.sin_addr.s_addr = INADDR_ANY;

    int dev_addrlen = sizeof(dev_addr);

    if (bind(sockfd, (struct sockaddr *)&dev_addr, dev_addrlen) < 0)
    {
        perror("bind err\n");
        return NULL;
    }

    if (listen(sockfd, 5) < 0)
    {
        perror("listen err");
        return NULL;
    }

    // 接收客户端的连接
    printf("wait  TCP NO.2 client connect\n");

    // 接收对端的地址
    acceptfd = accept(sockfd, (struct sockaddr *)&soft_addr, &dev_addrlen);
    if (acceptfd < 0)
    {
        perror("accept err");
        return NULL;
    }
    printf("tcp第二次连接成功\n");
    while (1)
    {
        memset(buf, 0, sizeof(buf));
        ret = recv(acceptfd, buf, sizeof(buf), 0);
        if (ret == 0)
        {
            break;
        }
        char bufname[32] = "";
        sprintf(bufname, "/mnt/config/%s.json", filename); // 需要改变存放文件的路径
        fd = open(bufname, O_WRONLY | O_CREAT | O_TRUNC, 0777);
        if (fd < 0)
        {
            perror("open  file  err \n");
        }

        write(fd, buf, ret);
    }
    cJSON *roots = cJSON_CreateObject();
    cJSON_AddItemToObject(roots, "type", cJSON_CreateNumber(2));
    cJSON *item = cJSON_CreateObject();
    cJSON_AddItemToObject(item, "flag", cJSON_CreateString("stop"));
    cJSON_AddItemToObject(roots, "data", item);
    char *p = cJSON_Print(roots);
    sprintf(buff, "%s", p);
    send(acceptfd, buff, sizeof(buff), 0);
    free(p);
    p = NULL;

    printf("文件接收完成\n");
    close(sockfd);
    close(acceptfd);
    close(fd);
}

int main(int argc, char const *argv[])
{
    int broadfd;
    int ret;
    char buff[64] = {0};
    char buff1[64] = {0};
    // 创建一个socket文件描述符
    broadfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (broadfd < 0)
    {
        perror("sock err");
        return -1;
    }
    int optvaludp = 1;
    setsockopt(broadfd, SOL_SOCKET, SO_REUSEADDR, &optvaludp, sizeof(optvaludp));

    // 配置网络信息
    struct sockaddr_in dev_addr;
    dev_addr.sin_family = AF_INET;
    dev_addr.sin_port = htons(8000); // 端口号
    dev_addr.sin_addr.s_addr = INADDR_ANY;

    int dev_addrlen = sizeof(dev_addr);

    if (bind(broadfd, (struct sockaddr *)&dev_addr, dev_addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }

    ssize_t len;
    char buf[N] = {0};
    struct sockaddr_in soft_addr;

    memset(buf, 0, N);

    while (1)
    {
        // 接收"five"搜索包
        len = recvfrom(broadfd, buf, N, 0, (struct sockaddr *)&soft_addr, &dev_addrlen);
        // 判断收到的数据是否"five"
        if (strcmp(buf, "five") != 0)
        {
            printf("not my five\n");
            continue;
        }
        else
            break;
    }
    // 回复yes，告诉QT客户端，我收到了搜索协议，并且回复地址
    printf("已接收到匹配广播!\n");
    sendto(broadfd, "yes", 4, 0, (struct sockaddr *)&soft_addr, dev_addrlen);
    // 启动TCP服务器，准备接收软件的升级文件
    int tcpfd = socket(AF_INET, SOCK_STREAM, 0);
    if (tcpfd < 0)
    {
        perror("sock err\n");
        return -1;
    }

    if (bind(tcpfd, (struct sockaddr *)&dev_addr, dev_addrlen) < 0)
    {
        perror("bind err\n");
        return -1;
    }

    // 监听套接字
    if (listen(tcpfd, 5) < 0)
    {
        perror("listen err\n");
        return -1;
    }

    // 接收客户端的连接
    printf("wait client connect\n");

    int optval = 1;
    setsockopt(tcpfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));

    int acceptfd;

    // 接收对端的地址
    acceptfd = accept(tcpfd, (struct sockaddr *)&soft_addr, &dev_addrlen);
    if (acceptfd < 0)
    {
        perror("accept err");
        return -1;
    }
    printf("tcp第一次连接成功\n");
    printf("new connect coming\n");
    printf("port:%d ip:%s\n", ntohs(soft_addr.sin_port), inet_ntoa(soft_addr.sin_addr));
    int a = 1;
    while (1)
    {
        memset(buf, 0, sizeof(buf));
        ret = recv(acceptfd, buf, sizeof(buf), 0);
        printf("%s\n", buf);
        // 对于tcp服务器来说,有三个返回值
        //>0:读到的字节个数
        //=0:客户端退出
        //<0:错误
        if (ret < 0)
        {
            perror("recv err\n");
            return -1;
        }
        else if (ret == 0)
        {
            printf("client exit\n");
            break;
        }
        else
        {
            cJSON *root = cJSON_Parse(buf);
            cJSON *item = cJSON_GetObjectItem(root, "type");
            int type = item->valueint;

            if (type == 1)
            {
                if (isFileInDirectory("/mnt/config/", "five.json"))
                {
                    cJSON *root = cJSON_CreateObject();
                    cJSON_AddItemToObject(root, "type", cJSON_CreateNumber(1));
                    cJSON_AddItemToObject(root, "result", cJSON_CreateNumber(0));
                    cJSON_AddItemToObject(root, "up_config", cJSON_CreateFalse());
                    char *p = cJSON_Print(root);
                    sprintf(buff1, "%s", p);
                    send(acceptfd, buff1, sizeof(buff1), 0);
                    printf("文件存在\n");
                    free(p);
                    p = NULL;
                }
                else
                {

                    cJSON *root = cJSON_CreateObject();
                    cJSON_AddItemToObject(root, "type", cJSON_CreateNumber(1));
                    cJSON_AddItemToObject(root, "result", cJSON_CreateNumber(0));
                    cJSON_AddItemToObject(root, "up_config", cJSON_CreateTrue());
                    char *p = cJSON_Print(root);
                    sprintf(buff1, "%s", p);
                    send(acceptfd, buff1, sizeof(buff1), 0);
                    printf("文件不存在\n");
                    free(p);
                    p = NULL;
                }
                printf("TCP第一次链接成功\n");
            }
            else if (type == 2 && a == 1)
            {
                printf("sdadasdadasds\n");
                cJSON *data = cJSON_GetObjectItem(root, "data");
                cJSON *itemfile_len = cJSON_GetObjectItem(data, "file_len");
                cJSON *itemfile_name = cJSON_GetObjectItem(data, "file_name");
                cJSON *itemflag = cJSON_GetObjectItem(data, "flag");
                cJSON *type = cJSON_GetObjectItem(root, "type");
                char *flag = itemflag->valuestring;

                if (strncmp(flag, "stop", 4) == 0)
                {
                    printf("停止\n");
                }
                else
                {
                    char *file_name = itemfile_name->valuestring;
                    int file_len = itemfile_len->valueint;
                    filename = itemfile_name->valuestring;
                }

                if (strncmp(flag, "start", 5) == 0)
                {
                    cJSON *roots = cJSON_CreateObject();
                    cJSON_AddItemToObject(roots, "type", cJSON_CreateNumber(2));
                    cJSON *item = cJSON_CreateObject();
                    cJSON_AddItemToObject(item, "flag", cJSON_CreateString("start"));
                    cJSON_AddItemToObject(roots, "data", item);
                    char *p = cJSON_Print(roots);
                    sprintf(buff, "%s", p);
                    send(acceptfd, buff, sizeof(buff), 0);
                    printf("buff:%s\n", buff);
                    pthread_create(&tid, NULL, handler, NULL);
                    free(p);
                    p = NULL;
                    a = 0;
                }
                else if (strncmp(flag, "stop", 4) == 0)
                {
                    pthread_join(tid, NULL);
                    printf("关闭线程\n");
                }
            }
            else if (type == 3)
            {
                cJSON *root = cJSON_CreateObject();
                cJSON_AddItemToObject(root, "type", cJSON_CreateNumber(3));
                cJSON_AddItemToObject(root, "result", cJSON_CreateNumber(0));
                char *p = cJSON_Print(root);
                sprintf(buff, "%s", p);
                send(acceptfd, buff, sizeof(buff), 0);
                printf("buff:%s\n", buff);
                if (send(acceptfd, buff, sizeof(buff), 0) < 0)
                {
                    perror("send err\n");
                }
                printf("isliving\n");
                free(p);
                p = NULL;
            }
        }
    }
    close(broadfd);
    close(tcpfd);
    close(acceptfd);
    return 0;
}
